package com.duanjw.springboot.mongodb.web;

import com.duanjw.springboot.mongodb.entity.User;
import com.duanjw.springboot.mongodb.repository.UserRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserRepository userRepository;


    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public User getByUserId(@PathVariable String id) {
        return userRepository.findById(id).orElse(new User());
    }

    @PostMapping
    public User addNewUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable String id) {
        User user = new User();
        user.setUserId(id);
        userRepository.deleteById(id);
        return "deleted: " + id;
    }

    @PutMapping
    public User update(@RequestBody User user) {
        return userRepository.save(user);
    }
}